<?php

namespace builder\uploads;

use common\helper\App;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;

/**
 * 文件上传七牛云
 * ```example
 * //main.php中组件定义
 * // 文件上传管理器(上传七牛云)
 * 'uploadManager' => [
 *      'class' => 'builder\uploads\Upload',
 *      'provider' => [
 *          'class' => 'builder\uploads\QiniuProvider',
 *          'webroot' => '',
 *          'web' => 'http://images.weshop.damanzj.com',
 *          'accessKey' => 'MNoIzTlulijH2dQ7mFbGQs_zG6_L_M0iYY8qlPuI',
 *          'secretKey' => 'B4w8MI35-lnitNnXn3HU-SHU4gLiQsq9qiolwS8t',
 *          'bucketName' => 'wx3c3shop',
 *      ],
 * ],
 * ```
 * @auther clevstn
 * @since ym2.0
 */
class QiniuProvider extends BaseProvider
{
    //完整域名，尾部不带反斜杠“/”。
    //public $web;
    //目录，根目录：空字符；目录结构：A 或 A/B，尾部不带反斜杠“/”。
    //public $webroot;
    /**
     * @var string 七牛令牌
     */
    public $accessKey;
    /**
     * @var string 七牛秘钥
     */
    public $secretKey;
    /**
     * @var string 空间名
     */
    public $bucketName;

    /**
     * {@inheritdoc}
     */
    protected function run($deleteTempFile = true)
    {
        $auth = new Auth($this->accessKey, $this->secretKey);
        $accessToken = $auth->uploadToken($this->bucketName);
        list($basename, $saveFilePath) = $this->generateUniqueFilePath();
        $this->link = '/' . $this->webroot . '/' . $basename;
        $uploadMgr = new UploadManager();
        try {
            @list(, $err) = $uploadMgr->putFile(
                $accessToken,
                $saveFilePath,
                $this->uploadFile->tempName,
                null,
                'application/octet-stream',
                false,
                null,
                'v2',
                4*1024*1024
            );
            if ($err != null) {
                /** 记录应用日志 */
                App::logError('【七牛云存储】', [
                    '文件信息：' => $this->result,
                    '接口响应：' => get_object_vars($err->getResponse()),
                ], 'qiniu-storage');

                $this->error = $err->message();
                return false;
            }
        } catch (\Throwable $e) {
            /** 记录应用日志 */
            App::logError('【七牛云存储】', [
                '文件信息：' => $this->result,
                '接口响应：' => get_object_vars($e),
            ], 'qiniu-storage');
            $this->error = $e->getMessage();
            return false;
        }

        return true;
    }
}